package service

import (
	"EnjoyWorking/model"
	"EnjoyWorking/utils"
	"EnjoyWorking/utils/storage"
	"errors"
)

type Project struct {}

func (service *Project) Insert(project *model.Project) error {
	//检验部门是否存在
	var total int64
	if err := storage.MySqlDb().Model(&model.Department{}).Where("id = ?", project.DepartmentID).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_DEPARTMENT_NOT_EXIST.String())
	}

	//检验用户是否存在
	if err := storage.MySqlDb().Model(&model.User{}).Where("id = ?", project.ManagerUserID).Count(&total).Error; err != nil {
		return err
	}

	if total == 0 {
		return errors.New(utils.CODE_USER_NOT_EXIST.String())
	}

	if err := storage.MySqlDb().Model(project).Where("name = ?", project.Name).Count(&total).Error; err != nil {
		return err
	}

	if total != 0 {
		return errors.New(utils.CODE_PROJECT_NAME_DUPLICATE.String())
	}

	return storage.MySqlDb().Create(project).Error
}

func (service *Project) FindList() (int64, []*model.Project, error) {
	var (
		err    error
		total  int64
		result = make([]*model.Project, 0)
	)

	if err = storage.MySqlDb().Model(&model.Project{}).Count(&total).Error; err != nil {
		goto ERR
	}

	if err = storage.MySqlDb().Model(&model.Project{}).
		Preload("Department").
		Preload("User").
		Find(&result).Error; err != nil {
		goto ERR
	}

	return total, result, nil
ERR:
	return 0, nil, err
}
